package com.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.pojo.MovieList;
import com.service.DyService;
import com.service.DyTypeService;
import com.service.SpecialFilmListService;
import com.service.SpecialService;
import com.util.DesUtil;
import com.util.HardUtil;
import com.util.MD5Util;
import com.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@SuppressWarnings("ALL")
@Component("TimeTaskUpdateDyInfoService")
public class TimeTaskUpdateDyInfoService {


    @Value("${server.port}")
    private String port;


    @Autowired
    @Qualifier("StringRedisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private DyTypeService dyTypeService;

    @Autowired
    private DyService dyService;

    @Value("${server.url}")
    private String server;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private SpecialService specialService;

    @Autowired
    private SpecialFilmListService specialFilmListService;


    @Value("${dy.tmp}")
    private String tmp;

    @Value("${dy.home}")
    private String home;

    private String downImage(String img, boolean rename) {


        File baseImage = new File(home + "/images");
        if (baseImage.exists() == false) {
            baseImage.mkdir();
        }
        String dir = StringUtils.getDir(img);
        String filename = StringUtils.getFilename(img);

        File imageBaseFile = new File(baseImage + dir);
        if (imageBaseFile.exists()) {
            imageBaseFile.mkdirs();
        }


        String newfilename = IdUtil.fastSimpleUUID() + ".png";
        String url = server + img;
        if (img.startsWith("http://") == true) {
            url = img;
        }


        try {
            if (rename) {
                File downfilename = new File(baseImage, newfilename);
                HttpUtil.downloadFile(url, downfilename);
            } else {
                File downfilename = new File(imageBaseFile, filename);
                HttpUtil.downloadFile(url, downfilename);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return newfilename;
    }





    public boolean enableDown() {
        int begin = 0;
        int end = 24;
        try {
            InputStream is = new FileInputStream("time.properties");
            Properties p = new Properties();
            p.load(is);
            String beginTime = p.getProperty("begin");
            String endTime = p.getProperty("end");
            begin = Integer.parseInt(beginTime);
            end = Integer.parseInt(endTime);
        } catch (Exception e) {
            // e.printStackTrace();
        }

        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        if (hour < begin && hour > end) {
            return false;
        }
        return true;
    }


    private List<MovieList> removeAll(List<MovieList> src, List<MovieList> target) {
        LinkedList<MovieList> result = new LinkedList<MovieList>(src); //大集合用linkedlist
        HashSet<MovieList> targetHash = new HashSet<MovieList>(target); //小集合用hashset
        Iterator<MovieList> iter = result.iterator(); //采用Iterator迭代器进行数据的操作

        while (iter.hasNext()) {
            MovieList m = iter.next();
            if (targetHash.contains(m)) {
                iter.remove();
            }
        }
        return result;
    }









    @Scheduled(cron = "7 0/10 * * * ?")
    public synchronized   void updateDyInfo() {
        List<MovieList> remoteList = null;
        String mainboardID = HardUtil.getMainBorId();
        String url = server + "/api/v1/getMovieBySite?mainboardID={1}";
        if (server.startsWith("http://172.") || server.startsWith("http://192.") || server.startsWith("http://10.")){
           // url = server + "/api/v1/getAllDy?mainboardID={1}";
        }
        String response = restTemplate.getForObject(url, String.class, mainboardID);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject != null) {
            int code = jsonObject.getInteger("code");
            if (code != 200) {
                System.out.println(jsonObject.getString("msg"));
                return;
            }

            //获取远程节目列表
            remoteList = jsonObject.parseArray(jsonObject.getString("data"), MovieList.class);
            //获取本地节目列表
            List<MovieList> localList = dyService.list();


            //比较
            List<MovieList> addList = new ArrayList(); //要新增的电影
            List<MovieList> removeList = new ArrayList();//要删除的电影
            if (remoteList != null) {
                addList = removeAll(remoteList, localList);
            }
            if (localList != null && remoteList != null) {

                removeList = removeAll(localList, remoteList);
            }
            //检测数据库存中存在电脑，文件不存在就下载
            List<MovieList> list = dyService.list();
            for (MovieList m : list) {



                String md5 = m.getMd5();
                File file = new File(home + "dy", md5);
                if (m.getCopyright_expiration_time() != null) {
                    long daoqiTime = m.getCopyright_expiration_time().getTime();
                    if (daoqiTime < System.currentTimeMillis()) {
                        m.setIs_it_on_the_shelf(0);//下架
                        //movieListDAO.updateById(m);//修改状态
                        dyService.updateById(m);

                    }
                }

                long id = m.getId();
                if (remoteList != null) {
                    for (MovieList r : remoteList) {
                        if (r.getId() == id) {
                            String image1 = r.getBig_poster();
                            String image2 = r.getLittle_poster();

                            BeanUtil.copyProperties(r, m, "md5", "isdown","local_img");

                            String localImg = m.getLocal_img();
                            boolean needDown = false;
                            if (localImg != null) {
                                File file1 = new File(home + "images/", localImg);
                                if (file1.exists() == false) {
                                    needDown = true;
                                }
                            } else {
                                needDown = true;
                            }

                            if (needDown) {
                                String resultImg = downImage(r.getBig_poster(), true);
                                m.setLocal_img(resultImg);
                            }

                            dyService.updateById(m);
                            //downImage(image2, false);
                            break;
                        }
                    }
                }


                try {
                    //拼接下载地址
                    String ip = m.getIp();
                    String dy_down_ip = (String)redisTemplate.boundValueOps("dy_down_ip").get();
                    String dy_down_port = (String)redisTemplate.boundValueOps("dy_down_port").get();
                    String dy_down_status = (String)redisTemplate.boundValueOps("dy_down_status").get();
                    if ("1".equals(dy_down_status) && StringUtils.isEmpty(dy_down_ip)==false){
                        ip = dy_down_ip;
                    }

                    if (ip == null || ip.trim().length() == 0) {
                        continue;
                    }
                    String downLoadUrl = ip;
                    if (ip.startsWith("http://") == false) {
                        downLoadUrl = "http://" + ip;
                    }
                    Integer port = m.getPort();
                    if (port == null) {
                        continue;
                    }
                    downLoadUrl = downLoadUrl + ":" + port;
                    //判断是否已下载
                    String path = m.getPath();
                    String name = m.getProgram_name();
                    String nameMd5 = MD5Util.getMD5(name);
                    if (path == null) {
                        path = "/";
                    }
                    if (path != null && path.startsWith("/res") == false) {
                        if (path.startsWith("/")) {
                            path = "/res" + path;
                        } else {
                            path = "res/" + path;
                        }
                    }

                    String downPath = path;
                    if ("1".equals(dy_down_status) && StringUtils.isEmpty(dy_down_ip)==false){
                        downPath = m.getMd5();
                        if (downPath==null){
                            String extFile = ".mp4";
                            int index = path.lastIndexOf('.');
                            if (index > -1) {
                                extFile = path.substring(index);
                            }
                            downPath =nameMd5+"."+extFile;
                        }
                    }
                    if (downPath != null && downPath.startsWith("/home")) {
                        downPath = downPath.replaceFirst("/home", "");
                    } else if (downPath != null && downPath.startsWith("home")) {
                        downPath = downPath.replaceFirst("home", "");
                    } else if (downPath != null && downPath.startsWith("/res")) {
                        downPath = downPath.replaceFirst("/res", "");
                    } else if (downPath != null && downPath.startsWith("res")) {
                        downPath = downPath.replaceFirst("res", "");
                    }

                    if (downPath != null && downPath.startsWith("/res")) {
                        downPath = downPath.replaceFirst("/res", "");
                    }
                    if (downPath != null && downPath.startsWith("res")) {
                        downPath = downPath.replaceFirst("res", "");
                    }

                    if (downPath.startsWith("/dy") == false || downPath.startsWith("dy") == false) {
                        if (downPath.startsWith("/")) {
                            downPath = "/dy" + downPath;
                        } else {
                            downPath = "/dy/" + downPath;
                        }
                    }
                    if (downPath != null && downPath.startsWith("/") == false) {
                        downPath = downPath + "/";
                    }
                    if (downPath.startsWith("/") == false) {
                        downPath = "/" + downPath;
                    }
                    downLoadUrl = downLoadUrl + downPath;


                    String extFile = ".mp4";
                    int index = path.lastIndexOf('.');
                    if (index > -1) {
                        extFile = path.substring(index);
                    }
                    //-------------------------------------------------------------------
                    String key = MD5Util.getMD5("1234@#$.Ab" + new SimpleDateFormat("yyyyMMddHH").format(new Date()));
                    downLoadUrl = downLoadUrl + "?key=" + DesUtil.encryptThreeDESECB(name, key);


                    File dyFile = new File(home + "dy/", nameMd5 + extFile);
                    File tmpFile = new File(tmp, name + extFile);
                    boolean downok = true;
                    if (dyFile.exists() == false) {
                        try {
                            downok = false;
                            if (enableDown() == true) {
                                HttpUtil.downloadFile(downLoadUrl, tmpFile, 1000 * 60 * 60 * 2);
                                //下载后改名
                                FileUtil.move(tmpFile, dyFile, false);
                                downok = true;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            downok = false;
                        }
                    }

                    if (downok)
                    {
                        m.setIsdown(1);
                    }
                    else {
                        m.setIsdown(0);
                    }

                    //m.setIsdown(1);
                    //movieListDAO.updateById(m);
                    String localImg = m.getLocal_img();
                    boolean needDown = false;
                    if (localImg != null) {
                        File file1 = new File(home + "images/", localImg);
                        if (file1.exists() == false) {
                            needDown = true;

                        }
                    } else if (localImg == null) {

                        needDown = true;
                    }

                    if (needDown) {
                        String resultImg = downImage(m.getBig_poster(), true);
                        m.setLocal_img(resultImg);
                    }


                    dyService.updateById(m);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

    }






}
